<template>
    <div class="search-container">
        <form action="/" class="search-from">
            <van-search v-model="searchText" show-action placeholder="请输入搜索关键词" @search="onSearch" @cancel="onCancel"
                background="#3296fa" @focus="onFocus" />
        </form>
        <SearchResult v-if="isResultShow" :searchText="searchText"></SearchResult>
        <SearchSuggestion v-else-if="searchText" :searchText="searchText" @search="onSearchText"></SearchSuggestion>
        <SearchHistory v-else :searchHistories="searchHistories" @updatasearchHistories="clearsearchHistories"
            @search="onSearch">
        </SearchHistory>
    </div>
</template>

<script>
import SearchHistory from './components/search-history.vue'
import SearchResult from './components/search-result.vue'
import SearchSuggestion from './components/search-suggestion.vue'
import { setItem, getItem } from '../../utils/storage'

export default {
    name: 'SearchIndex',
    components: {
        SearchHistory,
        SearchResult,
        SearchSuggestion
    },
    data() {
        return {
            searchText: '',
            isResultShow: false,
            searchHistories: getItem('toutiao_histories') || []
        };
    },
    methods: {
        onSearch(val) {
            this.isResultShow = true
            this.searchText = val
            const index = this.searchHistories.indexOf(val)
            if (index !== -1) {
                this.searchHistories.splice(index, 1)
            }
            this.searchHistories.unshift(val)
        },
        onCancel() {
            this.$router.back()
        },
        onFocus() {
            this.isResultShow = false
        },
        onSearchText(text) {
            this.searchText = text
            this.isResultShow = true
            this.searchHistories.unshift(text)
        },
        clearsearchHistories(arr) {
            this.searchHistories = arr
        }
    },
    watch: {
        searchHistories(newValue) {
            setItem('toutiao_histories', newValue)
        }
    }
}
</script>

<style scoped lang="less">
.search-container {
    padding-top: 108px;

    .search-from {
        width: 100%;
        position: fixed;
        top: 0;
        left: 0;
        z-index: 1;
    }

    .van-search__action {
        color: #fff;
    }
}
</style>